package xyz.zhno.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK动态代理
 * @author zh_o
 * @date 2020-11-17
 */
public class JdkDynamicProxyTest {

    public static void main(String[] args) {
        Object o = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), RealIdol.class.getInterfaces(), new BrokerHandler(new RealIdol()));
        ((Idol) o).sing();
    }

}

/**
 * 抽象角色
 */
interface Idol {

    /**
     * 原方法
     */
    void sing();

}

/**
 * 真实角色
 */
class RealIdol implements Idol {

    /**
     * 原方法
     */
    @Override
    public void sing() {
        System.out.println("sing......");
    }
}

/**
 * 实现 InvocationHandler
 */
class BrokerHandler implements InvocationHandler {

    private Object obj;

    public BrokerHandler(Object obj) {
        this.obj = obj;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("增强......");
        return method.invoke(obj, args);
    }

}